package com.fiill.audioplayer;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileInputStream;

import android.content.pm.PackageManager;
import android.os.Environment;
import android.widget.Toast;

import android.content.Intent;
import android.Manifest;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.UserHandle;
import android.util.Log;

import com.fiill.audioplayer.filelist.FileListFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 10086;
    private static final int REQUEST_EXTERNAL_STORAGE_PERMISSION = 10010;

    private AudioRecordManger mAudioRecordManger;
    private AudioTrackManager mAudioTrackManager;
    private String mOutChannelMaskStr;
    private String mAudioContextStr;
    private String mOutBitFormatStr;
    private String mPlaybackUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAudioRecordManger = AudioRecordManger.getInstance();
        mAudioTrackManager = AudioTrackManager.getInstance();

        findViewById(R.id.button_start_record).setOnClickListener(this);
        findViewById(R.id.button_stop_record).setOnClickListener(this);
        findViewById(R.id.button_start_play).setOnClickListener(this);
        findViewById(R.id.button_stop_play).setOnClickListener(this);
        findViewById(R.id.button_home).setOnClickListener(this);
        findViewById(R.id.button_quit).setOnClickListener(this);

        initSpinnerListener(R.id.spinner_audio_context);
        initSpinnerListener(R.id.spinner_channel_mask);
        initSpinnerListener(R.id.spinner_bit_format);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                              REQUEST_EXTERNAL_STORAGE_PERMISSION);
        } else {
             doOpenDirectory(Environment.getExternalStorageDirectory(), false);
        }

        startCmdService();
    }

    private void startCmdService(){
        Log.i("BAHAL_MAIN", "start Cmd Service ...");
        Intent rmServiceIntent = new Intent();
        rmServiceIntent.setClass(MainActivity.this, CmdService.class);
        startServiceAsUser(rmServiceIntent, UserHandle.CURRENT);
    }

    private boolean checkRecordPermission() {
        if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_EXTERNAL_STORAGE_PERMISSION) {
            if (grantResults. length >= 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doOpenDirectory(Environment.getExternalStorageDirectory(), false);
            } else {
                doOpenDirectory(new File("/mnt/bose"), false);
                Toast.makeText(this, "Please grant reading storage permission", Toast.LENGTH_SHORT).show();
            }
        } else  if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Record Permission granted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Record Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void doOpenDirectory(File path, boolean addToBackStack) {
        Fragment newFragment = FileListFragment.newInstance(this, path);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.replace(R.id.fragment_container, newFragment);

        if (addToBackStack) transaction.addToBackStack(null);
        transaction.commit();
    }

    private void initSpinnerListener(int spinner_id) {
        Spinner spinner = findViewById(spinner_id);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                String itemStr = (String) parentView.getItemAtPosition(position);
                if (spinner_id == R.id.spinner_bit_format) mOutBitFormatStr = itemStr;
                else if(spinner_id == R.id.spinner_channel_mask) mOutChannelMaskStr = itemStr;
                else if(spinner_id == R.id.spinner_audio_context) mAudioContextStr = itemStr;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_start_record:
                if(!checkRecordPermission()) {
                    break;
                }
                String rec_path = "/mnt/bose/111.wav";
                EditText et_rec = findViewById(R.id.et_rec_media_path);
                if (null != et_rec) rec_path = et_rec.getText().toString();
                mAudioRecordManger.startRecord(rec_path);
                break;

            case R.id.button_stop_record:
                mAudioRecordManger.stopRecord();
                break;

            case R.id.button_start_play:
                String media_path = null;
                EditText et = findViewById(R.id.et_play_media_path);
                if (null != et) media_path = et.getText().toString();
                mAudioTrackManager.startPlay(media_path, mAudioContextStr, mOutChannelMaskStr, mOutBitFormatStr);
                break;

            case R.id.button_stop_play:
                mAudioTrackManager.stopPlay();
                break;

            case R.id.button_quit:
                mAudioTrackManager.stopPlay();
                finish();
                break;

            case R.id.button_home:
                Intent homeIntent = new Intent("android.intent.action.MAIN");
                homeIntent.addCategory("android.intent.category.HOME");
                homeIntent.setFlags(1059988);
                startActivity(homeIntent);
                break;
            default:
                break;

        }
    }

    public void updatePlayBackEditText(String Url) {
        EditText et = findViewById(R.id.et_play_media_path);
        if (null != et) {
            et.setText(Url);
        }
    }

    public void updateRecEditText(String Url) {
        EditText et = findViewById(R.id.et_rec_media_path);
        if (null != et) {
            et.setText(Url + "/111.wav");
        }
    }
}
